package cn.xiangyuanpin.web;

import cn.xiangyuanpin.pojo.User;
import cn.xiangyuanpin.service.UserService;
import cn.xiangyuanpin.service.impl.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class UserServlet  extends BaseServlet{
    private UserService userService=new UserServiceImpl();

    protected void login(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String name= req.getParameter("username");
        String password= req.getParameter("password");
        if(userService.login(new User(name,password))==null){
            System.out.println("账号密码错误");
            req.setAttribute("msg","账号或密码错误");
            req.setAttribute("username",name);
            req.getRequestDispatcher("/pages/user/login.jsp").forward(req, resp);
        }else{
            System.out.println("登录成功");
            req.getSession().setAttribute("user",userService.login(new User(name,password)));
            req.getRequestDispatcher("/pages/user/login_success.jsp").forward(req, resp);
        }
    }

    protected  void  register(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String username= req.getParameter("username");
        String password= req.getParameter("password");
        String email= req.getParameter("email");
        String code= req.getParameter("code");
        System.out.println(code);
        //  System.out.println("adcde".equals(code));
        // System.out.println(code.equals("abcde"));
        if(code.equals("abcde")){
            if(userService.existsUsername(username)){
                System.out.println("用户名"+username+"已存在！");
                req.getRequestDispatcher("/pages/user/regist.jsp").forward(req, resp);
            }else{
                userService.registerUser(new User(username,password,email));
                req.getRequestDispatcher("/pages/user/regist_success.jsp").forward(req, resp);
            }
        }else{
            System.out.println("验证码["+code+"]错误");

            req.getRequestDispatcher("/pages/user/regist.jsp").forward(req, resp);
        }
    }
    protected void loginOut(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
              req.getSession().invalidate();
              resp.sendRedirect(req.getContextPath());
    }


}
